package william.list;

/**
 * @author ZhangShenao
 * @date 2024/1/14
 * @description <a href="https://leetcode.cn/problems/reverse-linked-list/description/">...</a>
 */
public class Leetcode206_反转链表 {
    private class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    /**
     * 使用pre、cur和next三个变量,记录链表节点
     * 遍历链表,修改pre、cur和next三个指针的指向
     * <p>
     * 时间复杂度O(N) 需要遍历一次链表
     * 空间复杂度O(1)
     */
    public ListNode reverseList(ListNode head) {
        //边界条件校验
        if (head == null) {
            return head;
        }

        //使用pre、cur和next三个变量,记录链表节点
        ListNode pre = null;
        ListNode cur = head;
        ListNode next = null;

        //遍历链表,修改pre、cur和next三个指针的指向
        while (cur != null) {
            //记录next
            next = cur.next;

            //反转指针
            cur.next = pre;

            //修改变量,继续遍历
            pre = cur;
            cur = next;
        }

        //最后cur==null,返回pre为反转后的头节点
        return pre;
    }
}
